package edu.spec.sms.service.impl;

import edu.spec.sms.dao.iface.IClazzDao;
import edu.spec.sms.dao.iface.IStudentDao;
import edu.spec.sms.model.Student;
import edu.spec.sms.service.iface.IStudentService;
import edu.spec.sys.model.enumeration.Status;
import edu.spec.sys.util.FileTool;
import edu.spec.sys.util.XlsTools;
import org.madgecko.basic.model.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Service
public class StudentService implements IStudentService {

	@Autowired
	private IStudentDao studentDao;
	@Autowired
	private IClazzDao clazzDao;

	@Override
	public void add(Student student) {
		// add student
		studentDao.add(student);
	}

	@Override
	public void delete(Integer id) {
		// delete student
		studentDao.delete(id);

	}

	@Override
	public void update(Student student) {
		studentDao.update(student);
	}

	@Override
	public Student load(Integer id) {
		return studentDao.load(id);
	}

	@Override
	public Student loadByXh(String xh) {
		return studentDao.loadByXh(xh);
	}

    @Override
    public Student loadByXhAndSfzh(String xh, String sfzh) {
        return studentDao.loadByXhAndSfzh(xh, sfzh);
    }

    @Override
	public Student loadByOpenId(String openId) {
		return studentDao.loadByOpenId(openId);
	}

	@Override
	public Pager<Student> findStudentByCon(Integer status, Integer clazzId, String con) {
		return studentDao.findStudentByCon(status, clazzId, con);
	}

	@Override
	public List<Student> listStudentByClazz(Integer clazzId) {
		return studentDao.listStudentByClazz(clazzId);
	}

	@Override
	public boolean importIn(MultipartFile file, HttpServletRequest req, HttpSession session) {
//		// 0.validate clazz
//		Clazz c = clazzDao.load(clazzId);
//		if(null==c){
//			throw new SysException("班级不存在.");
//		}
		// 1.import student
		String fullStorePath = FileTool.saveTempFile(file, req);
		File importFile = new File(fullStorePath);
		//此处Student的stuNum为String类型,所以excel里的学号也应该为文本类型
		Collection col = XlsTools.importExcel(importFile, Student.class, "");
		for(Object o : col){
			Student s = (Student)o;
//			s.setBjid(clazzId);
//			s.setBjmc(c.getName());
			s.setCreateDate(new Date());
			s.setStatus(Status.ENABLED);
			this.add(s);
		}
		// 2.update Clazz studentNumber
//		int orgClazzStudentNumber = c.getStudentNumber();
//		int newClazzSutdentNumber = orgClazzStudentNumber + col.size();
//		c.setStudentNumber(newClazzSutdentNumber);
//		clazzDao.update(c);
		importFile.delete();
		return true;
	}
}
